import React, { MutableRefObject, forwardRef, useEffect, useImperativeHandle, useState } from "react";
import "./index.scss";

interface Props {
    format?: string;
    time: number;
    onFinish?: () => void;
    ref?: any
}

const CountDown: React.FC<Props> = forwardRef((props, ref) => {
    const [resetTime, setResetTime] = useState<string>();
    const [isShow, setIsShow] = useState(false);
    const curDate = Date.now();
    let timer: NodeJS.Timeout;

    // useEffect(() => {
    //     reset();
    // }, [])

    useImperativeHandle(ref, () => ({
        start
    }))
    const start = () => {
        timer && clearInterval(timer);
        let time = props.time;
        if (("" + props.time).length === 10) {
            time = props.time * 1000;
        } else if (("" + props.time).length != 13) {
            return setResetTime("时间戳只能为10位或13位")
        }
        if (time - curDate>0) {
            setIsShow(true)
            formatTimeDifference(time - curDate, props.format)
            time -= 1000;
            timer = setInterval(() => {
                formatTimeDifference(time - curDate, props.format);
                time -= 1000;
                if (time <= curDate) {
                    props.onFinish?.();
                    clearInterval(timer)
                    setIsShow(false)
                }
    
            }, 1000)
        }
    }

    function formatTimeDifference(endTimestamp: number, format = "HH:mm:ss") {
        const msPerSecond = 1000;
        const msPerMinute = 60 * 1000;
        const msPerHour = msPerMinute * 60;
        const msPerDay = msPerHour * 24;

        const days = Math.floor(endTimestamp / msPerDay);
        const hours = Math.floor((endTimestamp % msPerDay) / msPerHour);
        const minutes = Math.floor((endTimestamp % msPerHour) / msPerMinute);
        const seconds = Math.floor((endTimestamp % msPerMinute) / msPerSecond);

        const padZero = (num: number) => num.toString().padStart(2, '0');
        const o = {
            "DD": days,
            "HH": hours,
            "mm": minutes,
            "ss": seconds
        }

        Object.entries(o).forEach(([key, value]) => {
            format = format.replace(key, padZero(value))
        })
        setResetTime(format)
    }

    return <>{isShow ? <span id="count_down">
        {resetTime}
    </span> : null}</>



});

export default CountDown;
